//
//  GSArticleViewController.m
//  GameSky
//
//  Created by lanou on 16/1/13.
//  Copyright © 2016年 NiRongfei. All rights reserved.
//

#import "GSArticleViewController.h"
#import "GSArticleView.h"
#import "GSCommentView.h"
#import "GSArticleTitleView.h"
#import "GSArticleADView.h"
#import "GSBottomADView.h"
#import "GSOptionView.h"
#import "GSNewsArticleModel.h"
#import "GSNewsCorrelationModel.h"
#import "IMYWebView.h"

#import "UMSocial.h"
#import "JTSImageViewController.h"

@interface GSArticleViewController () <IMYWebViewDelegate,UITableViewDataSource,UITableViewDelegate,UITextViewDelegate,GSWebViewDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;// 背景滚动视图
@property (nonatomic, strong) IMYWebView *webView;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) GSArticleView *articleView;// 文章视图
@property (nonatomic, strong) GSCommentView *commentView;// 评论视图
@property (nonatomic, strong) GSArticleTitleView *titleView;// 文章标题
@property (nonatomic, strong) GSArticleADView *topADView;// 广告1
@property (nonatomic, strong) GSBottomADView *bottomADView;// 广告2
@property (nonatomic, strong) GSOptionView *optionView;// 选项视图
@property (nonatomic, strong) GSInputView *inputView;// 输入视图

@property (nonatomic, strong) NSMutableArray *listDataArray;

@property (nonatomic, strong) GSNewsArticleModel *articleModel;
@property (nonatomic, strong) GSNewsADModel *ADModel;


@property (nonatomic, strong) UIScrollView *photoScrollView;


@property (nonatomic, assign) NSInteger scale;

@end

@implementation GSArticleViewController

- (NSMutableArray *)listDataArray
{
    if (!_listDataArray) {
        _listDataArray = [NSMutableArray array];
    }
    return _listDataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
    self.scale = 80;
    
    // 获得偏好设置里保存的WebView字体大小;
    NSNumber *number = [[NSUserDefaults standardUserDefaults]objectForKey:@"tag"];
    if (number.integerValue == 20 ) {
        self.scale = 80;
    }
    if (number.integerValue == 21 ) {
        self.scale = 100;
    }
    if (number.integerValue == 22 ) {
        self.scale = 120;
    }
    
    [self addSubviews];
    [self addGestures];
    [self loadData];    
}


/**
 *  加载数据
 */
- (void)loadData
{
    // 加载相关文章数据;
    NSMutableDictionary *paraDict1 = [NSMutableDictionary dictionary];
    paraDict1[@"request"] = @{@"contentId":self.contentID, @"contentType":@"news", @"pageIndex":@1, @"elementsCountPerPage":@5};
    [GSNetworkManager requestWithUrlStr:@"http://appapi2.gamersky.com/v2/TwoCorrelation" paraDict:paraDict1 method:POST success:^(NSURLResponse *response, NSData *data) {
        if (data) {
            NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSArray *resultArray = dataDict[@"result"];
            for (NSDictionary *subDict in resultArray) {
                GSNewsCorrelationModel *model = [[GSNewsCorrelationModel alloc] init];
                [model setValuesForKeysWithDictionary:subDict];
                [self.listDataArray addObject:model];
            }
            [self.tableView reloadData];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
    // 加载WebView数据;
    NSMutableDictionary *paraDict2 = [NSMutableDictionary dictionary];
    paraDict2[@"deviceType"] = @"iPhone5,3";
    paraDict2[@"deviceId"] = @"17E14E61-4069-4736-992D-EE596A7AECBC";
    paraDict2[@"os"] = @"iOS";
    paraDict2[@"osVersion"] = @"8.4";
    paraDict2[@"app"] = @"GSApp";
    paraDict2[@"appVersion"] = @"2.1.0";

    paraDict2[@"request"] = @{@"contentId":self.contentID,@"pageIndex":@1};
    [GSNetworkManager requestWithUrlStr:@"http://appapi2.gamersky.com/v2/TwoArticle" paraDict:paraDict2 method:POST success:^(NSURLResponse *response, NSData *data) {
        if (data) {
            NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSDictionary *resultDict = dataDict[@"result"];
            self.articleModel = [[GSNewsArticleModel alloc] init];
            [self.articleModel setValuesForKeysWithDictionary:resultDict];
            self.titleView.model = self.articleModel;
            self.articleView.model = self.articleModel;
            
            // 预处理HTML文本;
            NSString *htmlStr = [NSString stringWithFormat:@"<head><style>img{width:%fpx !important;}</style></head>%@", kScreenWidth - 10, self.articleModel.mainBody];
            NSString *str = [NSString stringWithFormat:@"width=\"%f\"", kScreenWidth - 10];
            htmlStr = [htmlStr stringByReplacingOccurrencesOfString:@"width=\"550\"" withString:str];
            htmlStr = [NSString stringWithFormat:@"<div id=\"webview_content_wrapper\">%@</div>",htmlStr];
            [self.webView loadHTMLString:htmlStr baseURL:nil];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
    // 加载广告数据;
    NSMutableDictionary *paraDict = [NSMutableDictionary dictionary];
    paraDict[@"deviceType"] = @"iPhone5,3";
    paraDict[@"deviceId"] = @"17E14E61-4069-4736-992D-EE596A7AECBC";
    paraDict[@"os"] = @"iOS";
    paraDict[@"osVersion"] = @"8.4";
    paraDict[@"app"] = @"GSApp";
    paraDict[@"appVersion"] = @"2.1.0";
    paraDict[@"request"] = @{};
    [GSNetworkManager requestWithUrlStr:@"http://appapi2.gamersky.com/v2/addetails" paraDict:paraDict method:POST success:^(NSURLResponse *response, NSData *data) {
        if (data) {
            NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSDictionary *resultDict = dataDict[@"result"];
            self.ADModel = [[GSNewsADModel alloc] init];
            [self.ADModel setValuesForKeysWithDictionary:resultDict];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

/**
 *  添加子视图
 */
- (void)addSubviews
{
    // 1.添加文章详情的背景;
    self.articleView = [[GSArticleView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [self.view addSubview:self.self.articleView];
    [self.articleView.navBar.leftButton addTarget:self action:@selector(backBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.articleView.navBar.rightButton addTarget:self action:@selector(optionBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
//    [self.articleView.lastPageBtn addTarget:self action:@selector(lastPageBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
//    [self.articleView.nextPageBtn addTarget:self action:@selector(nextPageBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.articleView.shareBtn addTarget:self action:@selector(shareBtnClick) forControlEvents:(UIControlEventTouchUpInside)];
    [self.articleView.commentUIBtn addTarget:self action:@selector(commentUIBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
    
    // 2.添加ScrollView作为背景;
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    // 夜间模式
    self.scrollView.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);
    self.scrollView.alwaysBounceVertical = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    [self.articleView insertSubview:self.scrollView belowSubview:self.articleView.navBar];

    // 3.添加文章标题信息;
    self.titleView = [[GSArticleTitleView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, 100)];
    [self.scrollView addSubview:self.titleView];
    
    // 4.添加WebView;
    self.webView = [[IMYWebView alloc] initWithFrame:CGRectMake(0, self.titleView.bottom, kScreenWidth, kScreenHeight - self.titleView.bottom)];
    self.webView.delegate = self;
    self.webView.scrollView.bounces = NO;
    self.webView.scrollView.scrollEnabled = NO;
    [self.webView sizeToFit];
    [self.scrollView addSubview:self.webView];
    // 监听夜间模式通知;
    [kNotificationCenter addObserver:self selector:@selector(webViewFallToNight) name:DKNightVersionNightFallingNotification object:nil];
    [kNotificationCenter addObserver:self selector:@selector(webViewComeToDawn) name:DKNightVersionDawnComingNotification object:nil];
    
    // 5.添加选项设置弹窗;
    self.optionView = [[GSOptionView alloc] initWithFrame:CGRectMake(kScreenWidth - 185, 60, 180, 150)];
    self.optionView.hidden = YES;
    self.optionView.delegate = self;
    [self.articleView addSubview:self.optionView];
    
    // 6.添加评论视图到屏幕右侧外不显示;
    self.commentView = [[GSCommentView alloc] initWithFrame:CGRectMake(kScreenWidth, 0, kScreenWidth, kScreenHeight)];
    [self.view addSubview:self.commentView];
    [self.commentView.navBar.leftButton addTarget:self action:@selector(commentBackBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
    
}
// 主界面导航栏返回按钮点击方法;
- (void)backBtnClick:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)shareBtnClick
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"568a3499e0f55a3a3f000047"
                                      shareText:@"友盟社会化分享让您快速实现分享等社会化功能，http://umeng.com/social"
                                     shareImage:kPHImage
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToQQ,UMShareToQzone,UMShareToWechatSession,UMShareToWechatTimeline,nil]
                                       delegate:nil];
}
// 主界面评论按钮点击方法;
- (void)commentUIBtnClick:(UIButton *)button
{
    [UIView animateWithDuration:0.5 animations:^{
        self.articleView.frame = CGRectMake(-kScreenWidth * 0.7, 0, kScreenWidth, kScreenHeight);
        self.commentView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    }];
}
// 评论界面返回按钮点击方法;
- (void)commentBackBtnClick:(UIButton *)button
{
    [UIView animateWithDuration:0.5 animations:^{
        self.articleView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        self.commentView.frame = CGRectMake(kScreenWidth, 0, kScreenWidth, kScreenHeight);
    }];
}
// 右上角设置按钮点击方法;
- (void)optionBtnClick:(UIButton *)button
{
    self.optionView.hidden = !self.optionView.hidden;
}

/**
 *  添加手势
 */
- (void)addGestures
{
    UIPanGestureRecognizer *leftPan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(leftPanAction:)];
    [self.view addGestureRecognizer:leftPan];
    
    UIPanGestureRecognizer *rightPan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(rightPanAction:)];
    [self.commentView addGestureRecognizer:rightPan];
}
// 文章界面左滑手势方法;
- (void)leftPanAction:(UIPanGestureRecognizer *)pan
{
    // 1.获得手势当前移动的距离;
    CGFloat x = [pan translationInView:pan.view].x;
    
    // 2.当左滑平移时,根据手势移动距离改变视图位置;
    if (x < 0) {
        CGRect articleFrame = self.articleView.frame;
        articleFrame.origin.x = x;
        self.articleView.frame = articleFrame;
        
        CGRect commentFrame = self.commentView.frame;
        commentFrame.origin.x = kScreenWidth + x * 1.5;
        
        if (commentFrame.origin.x < 0) {
            commentFrame.origin.x = 0;
        }
        self.commentView.frame = commentFrame;
        
        // 3.判断手势结束时移动距离,如果大于屛宽的1/3就弹出显示评论界面,否则收回评论界面到屏幕右侧不显示;
        if (pan.state == UIGestureRecognizerStateEnded) {
            if (x < -kScreenWidth / 3) {
                articleFrame.origin.x = -kScreenWidth * 0.7;
                commentFrame.origin.x = 0;
            } else {
                articleFrame.origin.x = 0;
                commentFrame.origin.x = kScreenWidth;
            }
            [UIView animateWithDuration:0.5 animations:^{
                self.articleView.frame = articleFrame;
                self.commentView.frame = commentFrame;
            }];
        }
    }
}
// 评论界面右滑手势方法;
- (void)rightPanAction:(UIPanGestureRecognizer *)pan
{
    // 1.获得手势当前移动的距离;
    CGFloat x = [pan translationInView:pan.view].x;
    
    // 2.当右滑平移时,根据手势移动距离改变视图位置;
    if (x > 0) {
        CGRect articleFrame = self.articleView.frame;
        articleFrame.origin.x = x * 0.7 - kScreenWidth * 0.7;
        self.articleView.frame = articleFrame;
        
        CGRect commentFrame = self.commentView.frame;
        commentFrame.origin.x = x;
        self.commentView.frame = commentFrame;
        
        // 3.判断手势结束时移动距离,如果大于屛宽的一半就收回显示评论界面,否则继续显示评论界面;
        if (pan.state == UIGestureRecognizerStateEnded) {
            if (x > kScreenWidth / 3 ) {
                articleFrame.origin.x = 0;
                commentFrame.origin.x = kScreenWidth;
            } else {
                articleFrame.origin.x = -kScreenWidth * 0.7;
                commentFrame.origin.x = 0;
            }
            [UIView animateWithDuration:0.5 animations:^{
                self.articleView.frame = articleFrame;
                self.commentView.frame = commentFrame;
            }];
        }
    }
}

#pragma mark - TableView代理方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.listDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.textLabel.text = [self.listDataArray[indexPath.row] title];
    return cell;
}

#pragma mark - WebView代理方法

- (BOOL)webView:(IMYWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    // 预防非图片内容的点击跳转;
    if ([request.URL.scheme isEqualToString:@"http"]) return NO;
    
    if ([request.URL.scheme isEqualToString:@"image-preview"]) {
        NSString *path = [request.URL.absoluteString substringFromIndex:[@"image-preview:" length]];
        path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        
        JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
        
        imageInfo.imageURL = [NSURL URLWithString:path];
        
        JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                               initWithImageInfo:imageInfo
                                               mode:JTSImageViewControllerMode_Image
                                               backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
        [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOffscreen];
        
        return NO;
    }
    return YES;
}

- (void)webViewDidFinishLoad:(IMYWebView *)webView
{
    // 1.设置TitleView的frame;
    CGFloat titleHeight = [GSArticleTitleView titleHeightForModel:self.articleModel];
    self.titleView.frame = CGRectMake(0, 64, kScreenWidth, titleHeight);
    
    // 2.预处理HTML图片并设置WebView的frame;
    [webView stringByEvaluatingJavaScriptFromString:@"function assignImageClickAction(){var imgs=document.getElementsByTagName('img');var length=imgs.length;for(var i=0;i<length;i++){img=imgs[i];img.onclick=function(){window.location.href='image-preview:'+this.src}}}"];
    [webView evaluateJavaScript:@"assignImageClickAction();" completionHandler:nil];
    
    // 获得WebView自适应高度;
    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"] floatValue];
    webView.frame = CGRectMake(0, self.titleView.bottom, kScreenWidth, height);
    // 获取WebView最佳尺寸;
    CGSize frame = [webView sizeThatFits:webView.frame.size];
    // 获取WebView显示内容实际高度(像素高度);
    CGFloat webHeight = [[webView stringByEvaluatingJavaScriptFromString: @"document.getElementById('webview_content_wrapper').offsetHeight + parseInt(window.getComputedStyle(document.getElementsByTagName('body')[0]).getPropertyValue('margin-top')) + parseInt(window.getComputedStyle(document.getElementsByTagName('body')[0]).getPropertyValue('margin-bottom'))"] floatValue];
    // 内容实际高度 = 内容高度 * 最佳尺寸高度 / 当前高度;
    webHeight = webHeight * frame.height / height;
    // 再次设置WebView实际高度;
    webView.frame = CGRectMake(0, self.titleView.bottom, kScreenWidth, webHeight);
    
    NSString *str = [NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%ld%%'", self.scale];
    [webView evaluateJavaScript:str completionHandler:nil];
    
    // 3.添加广告1;
    CGFloat topADHeight = 0;
    if (self.ADModel.icon1.length) {
        self.topADView = [[GSArticleADView alloc] initWithFrame:CGRectMake(0, webView.bottom, kScreenWidth, 100)];
        self.topADView.model = self.ADModel;
        [self.scrollView addSubview:self.topADView];
        
        topADHeight = self.topADView.height;
    }
    
    // 4.添加相关文章部分;
    CGFloat tableHeight = 0;
    if (self.listDataArray.count) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, webView.bottom + topADHeight, kScreenWidth, self.tableView.tableHeaderView.height + self.listDataArray.count * self.tableView.rowHeight) style:(UITableViewStylePlain)];
        self.tableView.scrollEnabled = NO;
        self.tableView.dataSource = self;
        self.tableView.delegate = self;
        self.tableView.rowHeight = 30;
        [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
        [self.scrollView addSubview:self.tableView];
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
        UIView *markView = [[UIView alloc] initWithFrame:CGRectMake(0, 10, 2, 20)];
        markView.backgroundColor = [UIColor orangeColor];
        [headerView addSubview:markView];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, kScreenWidth, 40)];
        label.text = @"相关阅读";
        [headerView addSubview:label];
        self.tableView.tableHeaderView = headerView;
        
        tableHeight = self.tableView.height;
    }
    
    // 5.添加广告2;
    CGFloat bottomADHeight = 0;
    if (self.ADModel.icon.length) {
        self.bottomADView = [[GSBottomADView alloc] initWithFrame:CGRectMake(0, webView.bottom + topADHeight + tableHeight, kScreenWidth, 200)];
        self.bottomADView.model = self.ADModel;
        [self.scrollView addSubview:self.bottomADView];
        
        bottomADHeight = self.bottomADView.height;
    }
    
    // 6.设置ScrollView的滚动范围;
    self.scrollView.contentSize = CGSizeMake(-kScreenWidth / 2, webView.bottom + topADHeight + bottomADHeight + tableHeight);
    
    
}

#pragma mark - 设置WebView字体大小

- (void)setFontOfWebView:(NSInteger)tag
{
    NSInteger scale = 80;
    switch (tag) {
        case 20:
            scale = 80;
            break;
        case 21:
            scale = 100;
            break;
        case 22:
            scale = 120;
            break;
        default:
            break;
    }
    // 改变WebView字体大小;
    NSString *str = [NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%ld%%'", scale];
    [self.webView evaluateJavaScript:str completionHandler:nil];
    // 保存偏好设置;
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:tag] forKey:@"tag"];
}

#pragma mark - 通知方法

- (void)webViewFallToNight
{
    [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.background='#222222'"];
}

- (void)webViewComeToDawn
{
    [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.background='#FFFFFF'"];
}
// 移除通知;
- (void)dealloc
{
    [kNotificationCenter removeObserver:self];
}

@end
